<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->

      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            class="input-with-select"
          >
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" @click="showAddUser">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 数据列表 -->
      <el-table :data="userList" border style="width: 100%" stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="操作" width="200px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              size="mini"
              @click="editUserInfo(scope.row.id)"
              icon="el-icon-edit"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 设置按钮 -->
            <el-tooltip class="item" effect="dark" content="设置" placement="top-start">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="40%">
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        ref="addFormRef"
        inline
        label-width="80px"
        label-position="rigth"
        :rules="addFormRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="moblie">
          <el-input v-model="addForm.moblie"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogClosed">重置</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog title="添加用户" :visible.sync="editDialogVisible" width="40%">
      <!-- 内容主体区域 -->
      <el-form :model="editForm" ref="editFormRef" inline label-width="80px" label-position="rigth">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="moblie">
          <el-input v-model="editForm.moblie"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeEdit">取消</el-button>
        <el-button type="primary" @click="editUserInfoSave">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="30%">
      <div>
        <p>当前用户:{{userInfo.password}}</p>
        <p>当前角色:{{userInfo.role_name}}</p>
        <p>
          分配新角色:
          <el-select v-model="selectRole" placeholder="请选择分配角色">
            <el-option
              v-for="item in roleData"
              :key="item.id"
              :label="item.roleName"
              :value="item.roleName"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button>取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //   邮箱验证规则
    var checkEmail = (rule, value, cb) => {
      //验证邮箱正则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cd();
      }
      cb(new Error("请输入合法邮箱"));
    };

    //验证手机号
    var checkMobile = (rule, value, cb) => {
      // 验证手机号
      const regMoblie = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/;
      if (regMoblie.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法手机号！"));
    };

    return {
      //获取用户列表的参数对象
      queryInfo: {
        query: "",
        pagesize: 2,
        pagenum: 1
        // 分页数量
      },
      userList: [],
      total: 0,
      dialogVisible: false,
      addForm: {
        username: "",
        email: ""
      },
      editForm: {},
      editDialogVisible: false,
      addFormRules: {
        username: [
          {
            required: true,
            min: 3,
            max: 5,
            message: "长度在 3 到 5 个字符",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "请输入密码!",
            max: 10,
            trigger: "blur"
          }
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱!"
          },
          {
            validator: checkEmail,
            trigger: "blur"
          }
        ],
        moblie: [
          {
            required: true,
            message: "请输入手机号!"
          },
          {
            validator: checkMobile,
            trigger: "blur"
          }
        ]
      },
      //分配角色对话框
      setRoleDialogVisible: false,
      //需要被分配角色的用户信息
      userInfo: [],
      // 所有角色的数据列表
      roleData: [],
      // 选中角色id
      selectRole: ""
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 获取用户信息
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      console.log(res.data);
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    //   监听pagesize改变的事件
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    //监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 显示添加用户列表
    showAddUser() {
      this.dialogVisible = !this.dialogVisible;
    },
    // 改变用户状态
    async userStateChange(userinfo) {
      console.log(userinfo);
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.errro("更新状态失败！");
      }
      this.$message.success("更新成功！");
    },
    //添加用户重置对话框事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //添加用户
    addUser() {
      console.log(this.$refs, "111111111111");
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        //可以发起添加用户的网络请求
        const { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status !== 201) return this.$message.error("添加失败!");
        this.$message.success("添加成功！");
        //隐藏添加对话框
        this.dialogVisible = false;
        //重新获取用户数据
        this.getUserList();
      });
    },
    //编辑用户信息
    async editUserInfo(id) {
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) return this.$message.error("修改失败");
      this.editForm = res.data;
      this.editDialogVisible = !this.editDialogVisible;
    },
    closeEdit() {
      this.$refs.editFormRef.resetFields();
      this.editDialogVisible = false;
    },
    //修改用户信息提交
    editUserInfoSave() {
      console.log(this.editForm.id, "111");
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        //发起修改用户信息的数据请求

        const { data: res } = await this.$http.put(
          "/users" + this.editForm.id,
          {
            email: this.editForm.email,
            moblie: this.editForm.moblie
          }
        );
      });

      if (res.meta.status !== 200) {
        return this.$message.error("更新失败！");
      }

      this.editDialogVisible = false;
      this.getUserList();
      this.$message.success("更新成功！");
    },

    //删除用户
    removeUserById(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("users/" + id);
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.getUserList();
        })
        .catch(() => {
          //捕获错误
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 分配角色按钮对话框
    async setRole(userInfo) {
      this.userInfo = userInfo;

      //  展示对话框之前显示所有角色列表

      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error("获取失败");

      this.roleData = res.data;
      this.setRoleDialogVisible = true;
    },
    // 点击按钮 分配角色
    async saveRoleInfo() {
      if (!this.selectRole) {
        return this.$message.error("请选择要分配的角色");
      }
      console.log(this.userInfo.id)
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectRole
        }
      );

      if (res.meta.status !== 200) return this.$message.error("更新角色失败");

      this.$message.success("更新角色成功！");
      this.getUserList();
      this.setRoleDialogVisible = false;
      this.selectRole = "";
    }
  }
};
</script>

<style lang="less" scoped>
.box-card {
  margin-top: 20px;
}
.el-table {
  margin-top: 30px;
}
</style>